package com.yuanwushe.blue.onceandroid;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.yuanwushe.blue.models.Book;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.util.List;

import javax.sql.DataSource;

public class DatabaseActivity extends AppCompatActivity {

    public static String DATABASE_TAG = "database";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database);
        init();
    }

    private void init(){
        Button button = findViewById(R.id.create_database);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Connector.getDatabase();
            }
        });

        Button button1 = findViewById(R.id.add_database);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Book book = new Book();
                book.setName("第一行代码");
                book.setAuthor("作者");
                book.setPages(500);
                book.setPrice(16.96);
                book.save();
            }
        });

        Button button2 = findViewById(R.id.update_database);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Book book = new Book();
                book.setPrice(10.96);
                book.updateAll("name = ? and author = ?", "第一行代码", "作者");
            }
        });

        Button button3 = findViewById(R.id.select_database);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<Book> books = DataSupport.select("name", "author", "pages", "price").where("pages > ?", "400").order("pages").limit(10).find(Book.class);
                for (Book book : books) {
                    Log.d(DatabaseActivity.DATABASE_TAG, book.toString());
                }
            }
        });

        Button button4 = findViewById(R.id.delete_database);
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DataSupport.deleteAll(Book.class, "price < ?", "15");
            }
        });
    }
}
